<?php

namespace app\manage\controller;
use think\Request;
use app\common\model\Dev_info;
use app\common\model\Company_dev;
use app\common\model\Alarm_table;
class Dev extends Common
{
	/**
	 * 设备列表
	 * @return [type] [description]
	 */
	public function lists(){
        $state = input('get.state',0);
        $search = input('get.search','');

        $where = false;
        $pageParam = [];

        if($state){
        	switch ($state) {
        		case '1':
        			$where['state'] = 'activated';
        			break;
        		case '2':
        			$where['state'] = 'inactive';
        			break;
        		default:
        			break;
        	}
        	$pageParam['query']['state'] = $search;
        }
            
        if($search){
            $where['guid1|name'] = array('like','%'.$search.'%');
            $pageParam['query']['search'] = $search;
        }

		$devModel = new Company_dev();
		$data = $devModel->getDevAll($where,'a_time desc','*',15,$pageParam);

		$res = [
			'data'=>$data,
			'search'=>$search,
			'state'=>$state,
			'title'=>'设备列表'
		];
		return view('',$res);
	}

	/**
	 * 设备详情
	 * @return [type] [description]
	 */
	public function dinfos(){
		$uid = session('user.id');
		$id = input('id');
		$devModel = new Dev_info();
		$info = $devModel->getOne(['owner'=>29,'id'=>1]);
		$res = [
			'title'=>'设备详情',
			'info'=>$info
		];
		return view('',$res);
	}

    /**
     * 警报列表
     * @return [type] [description]
     */
    public function alarms(){
        $devid = input('get.devid', '');
        //警报类型
        $type = input('get.type', '');
        //警报状态
        $state = input('get.state', '');

        $startTime = input('get.startTime', false);
        $startTime = preg_replace('/\+/', ' ', $startTime);

        $endTime = input('get.endTime', false);
        $endTime = preg_replace('/\+/', ' ', $endTime);

        $where = array();
        $pageParam = array();
        if($devid){
            $where['guid1'] = $devid;
            $pageParam['query']['guid1'] = $devid;
        }

        //警报类型
        if($type) {
            switch ($type){
                //离线报警
                case '1':
                    $where['alarm_type'] = 'offline';
                    break;
                //异常报警
                case '2':
                    $where['alarm_type'] = 'abnormal';
                    break;
            }
            $pageParam['query']['type'] = $type;
        }

        //警报状态
        if($state) {
            switch ($state){
                //离线报警
                case '1':
                    $where['state'] = 'end';
                    break;
                    //异常报警
                case '2':
                    $where['state'] = 'last';
                    break;
            }
            $pageParam['query']['state'] = $state;
        }

        //时间
        if($startTime && $endTime){
            $where['st'] = array('gt', strtotime($startTime));
            $where['et'] = array('lt', strtotime($endTime));

            $pageParam['query']['startTime'] = $startTime;
            $pageParam['query']['endTime'] = $endTime;
        } 

        $alarmModel = new Alarm_table();
        $pageSize = 20;
        $field = 'guid1,alarm_type,state,st,et,reason';
        $data = $alarmModel->field($field)->order('st desc')->where($where)->paginate($pageSize,false,$pageParam);

        $res = [
            'data'=>$data,
            'startTime'=>$startTime,
            'endTime'=>$endTime,
            'state'=>$state,
            'type'=>$type,
            'devid'=>$devid,
            'title'=>'警报列表'
        ];

        return view('',$res);
    }

	/**
	 * 设备导出execl表
	 * @return [type] [description]
	 */
	public function adev(){
		$state = input('get.active','inactive');
        if(!in_array($state, array('activated', 'inactive', 'all'))) die();

        vendor('PHPExcel.Classes.PHPExcel');
        $phpExcel = new \PHPExcel();
        $letter = array('A','B', 'C', 'D', 'E', 'F','G','H','I','J','K','L','M','N','O');
        $title = array('设备号', '校验码', '加密秘钥',"设备添加码",'型号', '设备名称','制造商','状态');
        foreach ($title as $k => $v){
            $phpExcel->getActiveSheet()->setCellValue($letter[$k].'1', $title[$k]);
        }

        if($state != 'all') $where['state'] = $state;

        $devModel = new Company_dev();

        $field = 'guid1,guid2,key,vcode,model,name,maker,state';
        $rows = $devModel->devAll($where,$field);
        if($rows){
            $rows = json_decode(json_encode($rows),true);
        }else{
            $this->error('暂无设备');
        }
        
        $stateTable = array('inactive' => '未激活', 'activated' => '已激活');

        foreach ($rows as $k => &$v){
            $i = 0;
            $v['state'] = $stateTable[$v['state']];
            foreach ($v as $key => $val){
                $phpExcel->getActiveSheet()->setCellValue($letter[$i].($k+2), $val);
                $i++;
            }
        }
        unset($v);

        $filename = '设备列表导出-'.date("Y-m-d").'.xlsx';
        //清除缓存区,避免乱码
        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename="'.$filename.'"');
        header("Content-Transfer-Encoding:binary");
        $write=\PHPExcel_IOFactory::createWriter($phpExcel,'Excel2007');
        $write->save('php://output');
	}

    /**
     * 设备警报导出excel
     * */
    public function alarmExport(){
        $start = input('start', false);
        $end = input('end', false);

        $dev_id = input('dev_id');

        $where = array();
        if($start && $end && $start<$end){
            $where['st'] = array('egt',$start);
            $where['et'] = array('elt',$end);
        }else{
            $this->error('错误操作');
        }

        if($dev_id){
            $where['guid1'] = $dev_id;
        }

        $alarmModel = new Alarm_table();
        $res = $alarmModel->devAll($where);

        if(empty($res)){
            $this->error('暂无数据');
        }

        vendor('PHPExcel.Classes.PHPExcel');
        $phpExcel = new \PHPExcel();
        $letter = array('A','B', 'C', 'D', 'E', 'F','G','H','I','J','K','L','M','N','O');
        $title = array('设备号', '警报类型', '警报状态', '警报触发时间', '警报结束时间', '描述');
        foreach ($title as $k => $v)
            $phpExcel->getActiveSheet()->setCellValue($letter[$k].'1', $title[$k]);

        $alarmTypeTable = array('offline' => '离线警报', 'abnormal' => '异常警报');
        $alarmStateTable = array('end' => '已解除', 'last' => '持续中');

        foreach ($res as $k => $v){
            //设备号
            $phpExcel->getActiveSheet()->setCellValue($letter[0].($k+2), $v['guid1']);
            //警报类型
            $phpExcel->getActiveSheet()->setCellValue($letter[1].($k+2), $alarmTypeTable[$v['alarm_type']]);
            //警报状态
            $phpExcel->getActiveSheet()->setCellValue($letter[2].($k+2), $alarmStateTable[$v['state']]);
            //开始时间
            $phpExcel->getActiveSheet()->setCellValue($letter[3].($k+2), date('Y-m-d H:i:s', $v['st']));
            //结束时间
            if($v['et'] == -1) $phpExcel->getActiveSheet()->setCellValue($letter[4].($k+2), '尚未结束');
            else $phpExcel->getActiveSheet()->setCellValue($letter[4].($k+2), date('Y-m-d H:i:s', $v['et']));
            //描述
            $phpExcel->getActiveSheet()->setCellValue($letter[5].($k+2), date($v['reason']));
        }

        $filename = '警报记录导出-'.date("Y-m-d").'.xlsx';
        //清除缓存区,避免乱码
        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename="'.$filename.'"');
        header("Content-Transfer-Encoding:binary");
        $write=\PHPExcel_IOFactory::createWriter($phpExcel,'Excel2007');
        $write->save('php://output');
    }

    /**
     * 申请设备(一台 或 多台)
     * @return [type] [description]
     */
    public function applydev(){
        $uid = session('user.id');
        $devs = session('user.devs');

        $val = input("post.vals");
        $type = input("post.types");
        $type = $type?1:0;

        set_time_limit(0);

        $companyModel = new Company_dev();
        if($type){
            //申请一台设备(先大写 转 小写)
            $val = strtolower($val);
            //判断是否有中文,长度是否大于6
            if(preg_match("/[\x7f-\xff]/",$val)){
                exit(json_encode(array("code"=>false,"msg"=>"设备编号中不得有中文")));
            }else{
                if(strlen($val)>6){
                    exit(json_encode(array("code"=>false,"msg"=>"设备编号中不得超过6位")));
                }
            }
            //先查看设备是否存在
            $istrue = $companyModel->guidOnly($val);
            if($istrue){
                //进行 添加单台设备
                $companyModel->addDevs($uid,$val);

                $data["code"] = true;
                $data["msg"] = "添加成功";

                array_push($devs,$val);
                $_SESSION["devs"] = $devs;
            }else{
                $data["code"] = false;
                $data["msg"] = "此设备编号已经存在";
            }
        }else{
            //添加多台
            if(is_numeric($val)){
                $devs = $companyModel->numapply($uid,$val);

                $data["code"] = true;
                $data["msg"] = $devs;

                $devArr = array_combine($_SESSION["devs"],$devs);
                $_SESSION["devs"] = $devArr;
            }else{
                $data["code"] = false;
                $data["msg"] = "请输入数字";
            }
        }

        exit(json_encode($data));
    }

    /**
     * 生成  微信|APP 二维码 AJAX
     * @param [string] dev_id [设备号]
     * @param [string] type [1:微信 2:APP]
     * @return [json] [数组 二维码地址]
     */
    public function dcode(){

        $dev_id = input("post.dev_id");
        $type = input("post.type",1);

        $companyModel = new Company_dev();
        $res = $companyModel->getOne(['guid1'=>$dev_id],'id');
        if($res){
            if($type==1){
                //微信
                $data = $companyModel->createCode($dev_id);
            }else{

                //手机app二维码

            }

        }else{
            $data = array(
                 "code"=>false,
                 "msg"=>"设备号有误"
            );
        }
        dump($data);
        exit;
        exit(json_encode($data));
    }

    /**
     * 下载  微信|APP 二维码 GET
     * @param [string] [dev_id] [设备号]
     * @param [string] types [1:微信 2:APP]
     */
    public function downFile(){

        $dev_id = input("get.dev_id");
        $types = input("get.types",1);


        $uid = session('user.id');

        $companyModel = new Company_dev();

        if($types==1){
            //微信
            $companyModel->downWchatCode($dev_id);
        }else{
            //APP
            $companyModel->createAppCode($dev_id,1);
        }
    }

    /**
     * 批量下载微信二维码到本地
     */
    public function downWechatTwo(){
        $dev_id = input("get.devids");
        $uid = session('user.id');
        if(!$uid || !$dev_id){
            exit;
        }

        $devArr =  explode("-",$dev_id);

        // $companyModel = new Company_dev();
        foreach ($devArr as $key => $value) {
            // $devModel->downWchatCode($value);

            $path = config("WETCHAT_CODE");
            $filename = $path.$value.".jpg";

            download_by_path($filename);
        }
    }

}